package org.tangdao.modules.sys.web;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.tangdao.common.config.Global;
import org.tangdao.common.lang.StringUtils;
import org.tangdao.common.suports.BaseController;
import org.tangdao.modules.sys.model.domain.User;
import org.tangdao.modules.sys.service.IUserService;
import org.tangdao.modules.sys.service.impl.PasswordEncoderService;
import org.tangdao.modules.sys.utils.UserUtils;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;

/**
 * <p>
 * 用户表 前端控制器
 * </p>
 *
 * @author ruyang
 * @since 2019-07-02
 */
@Controller
@RequestMapping("${adminPath}/sys/user")
public class UserController extends BaseController {

	@Autowired
	private IUserService userService;
	
	@Autowired
	private PasswordEncoderService passwordEncoderService;

	@RequestMapping("/listData")
	public @ResponseBody IPage<User> listData(User user, HttpServletRequest request) {
		QueryWrapper<User> queryWrapper = new QueryWrapper<User>();
		if (StringUtils.isNotBlank(user.getStatus())) {
			queryWrapper.eq("status", user.getStatus());
		}
		if (StringUtils.isNotBlank(user.getUserType())) {
			queryWrapper.eq("user_type", user.getUserType());
		}
		if (StringUtils.isNotBlank(user.getUsername()) || StringUtils.isNotBlank(user.getNickname())) {
			queryWrapper.like("username", user.getUsername()).or().like("nickname", user.getNickname());
		}
		return this.userService.page(user.getPage(), queryWrapper);
	}

	@PostMapping(value = "save")
	public @ResponseBody String save(User user, Model model) {
		this.userService.updateUserinfo(user);
		return renderResult(Global.TRUE, "更新成功");
	}

	@RequestMapping(value = "/pass")
	public String formAuthDataScope(Model model, HttpServletRequest request) {
		User user = UserUtils.getUser();
		model.addAttribute("user", user); // 设置当前用户信息
		return "modules/user/pass";
	}

	/**
	 * 保存用户授权数据权限
	 */
	@RequestMapping(value = "savePassData")
	@ResponseBody
	public String saveAuthDataScope(String password, String oldPassword, HttpServletRequest request) {
		User user = UserUtils.getUser();
		boolean validate = passwordEncoderService.validatePassword(oldPassword, user.getPassword());
		if(validate) {
			//更新密码
			this.userService.updatePassword(user.getUserCode(), password);
			return renderResult(Global.TRUE, "更新成功");
		}
		return renderResult(Global.FALSE, "旧的登录密码验证失败");
		
	}

}
